package com.iwhalecloud.bss.kite.cucc.service.order;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpCallClient;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.ztesoft.bss.common.util.PropertiesUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.callclient.service.IOrderQueryService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.entity.InfService;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteBase64Util;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IAttachmentService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.req.QryStockAttachMentUrlReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.rsp.QryStockAttachMentUrlRspDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.login.auth.CuccAuthLoginInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ContractDictionaryChildrenDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ContractDictionaryDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.order.FileVO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.callclient.service.ICuccQueryInfService;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteHttpUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.ContractBody;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.attr.ContractBodyMapper;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.CallClientUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import tk.mybatis.mapper.entity.Example;

import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

@Service("attachmentService")
public class AttachmentService implements IAttachmentService {

    @Autowired
    private IInfServiceBus infServiceBus;

    @Autowired
    private ContractBodyMapper contractBodyMapper;

    @Autowired
    private ICustReceptionService custReceptionService;

    @Override
    public String attachView(String filePath, String fileName, boolean isStockAttachment) {
        Map<String, Object> param = new HashMap<>();
        //如果是存量（集客）的附件,那么要调接口获取文件的真实url,并且将文件的扩展名组装到url,送到预览接口
        if (isStockAttachment) {
            QryStockAttachMentUrlReqDTO qryStockAttachMentUrlReqDTO = new QryStockAttachMentUrlReqDTO();
            qryStockAttachMentUrlReqDTO.setEsbFileName(filePath);
            LoginInfo loginInfo = ContextUtil.getLoginInfo();
            qryStockAttachMentUrlReqDTO.setProvinceCode(loginInfo.getUserInfo().getPostProvinceNbr());
            QryStockAttachMentUrlRspDTO qryStockAttachMentUrlRsp = this
                .getStockAttachmentUrl(qryStockAttachMentUrlReqDTO);
            if (!KiteObjectUtils.isEmpty(qryStockAttachMentUrlRsp)) {
                filePath = qryStockAttachMentUrlRsp.getUrl();
            }
            if (KiteStringUtils.isNotEmpty(filePath)) {
                String fileType = fileName.split("\\.")[1];
                filePath = new StringBuffer(filePath).append("&fileType=type.").append(fileType).toString();
            }
        }
        param.put("requestId", LocalTokenUtil.getTransId());
        param.put("sourceMall", "3"); // 来源触点
        param.put("filePath", filePath);
        param.put("wmContent", "销售中心"); // 水印内容
        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("ATTACHMENT_PREVIEW_REQ", param);
        Map<String, Object> requestMap = LocalTokenUtil.getParamMap(uniBssBody);
        requestMap.put("OP_CODE", "json_GEorderCenter_otherService_attachmentPreview");
        InfServiceHelper.adaptGray(requestMap, param);

        try {
            String data;
            if (CallClientUtils.callByHttp()) {
                data = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
            }
            else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                data = infExchangeService.exchange(new JSONObject(requestMap));
            }            if (KiteStringUtils.isEmpty(data)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("预览链接获取失败");
            }
            Map<?, ?> result = LocalTokenUtil.checkRespParamAndGetObject(data, "ATTACHMENT_PREVIEW_RSP", Map.class);
            if (!KiteStringUtils.equals(KiteMapUtils.getString(result, "code"), LocalInfConsts.UNI_BSS_BODY_RESULT_SUCCESS)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut(KiteMapUtils.getString(result, "message"));
            }
            return KiteMapUtils.getString(result, "data");
        }
        catch (Exception e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("预览链接获取失败");
        }
        return "";
    }

    @Override
    public FileVO uploadAttachment(String fileName, byte[] bytes) {
    	IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
		InfService infService = orderQueryService.queryServiceBySvcCode(CallClientEnum.UPLOAD_FILE.getServiceCode(),
				CallClientEnum.UPLOAD_FILE.getCenterCode());
        if (infService == null) {
            ErrorConsts.SERVICE_UNREGISTERED.throwOut(
                    CallClientEnum.UPLOAD_FILE.getCenterCode() + ":" + CallClientEnum.UPLOAD_FILE.getServiceCode());
        }
        String url = SpringUtil.getBean(ICuccQueryInfService.class).getUrlByType(infService);
        String data = KiteHttpUtils.postByte(url, bytes, fileName);
        FileVO fileVO = JsonUtils.parseObject(data, FileVO.class);
        return fileVO;
    }

    @Override
    public List<ContractDictionaryDTO> queryContractDictionary() {
        UserInfo userInfo = ContextUtil.getLoginInfo().getUserInfo();
        // 查询时新增省份本部信息
        Example examplePar = new Example(ContractBody.class);
        examplePar.createCriteria()
            .andEqualTo("provinceCode", userInfo.getPostProvinceNbr());
        List<ContractBody> bodyListPar = contractBodyMapper.selectByExample(examplePar);
        Example example = new Example(ContractBody.class);
        List<ContractBody> bodyList = new ArrayList<>();
        bodyList.addAll(bodyListPar);
        if (KiteStringUtils.equals("T", DcSystemParamCache.getDcParamVal("20210202000"))) {
            String authSessionId = String.valueOf(ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("session_id"));
            CuccAuthLoginInfoDTO cuccAuthLoginInfo = custReceptionService.pretendLogin(authSessionId);
            if (cuccAuthLoginInfo != null) {
                // 是否总部工号判断
                if (KiteStringUtils.equals("0", String.valueOf(cuccAuthLoginInfo.getOrgInfo().getOrgLevel()))) {
                    example.clear();
                    example.createCriteria()
                        .andEqualTo("provinceCode", "09");
                    bodyList = contractBodyMapper.selectByExample(example);
                }
            }
        }
        List<ContractBody> tempBodyList = new ArrayList<>(bodyList);
        Map<String,List<ContractBody>> mapList = new HashMap<>();
        tempBodyList.stream().collect(Collectors.groupingBy(ContractBody::getFirstBodyCode)).forEach(mapList::put);
        List<ContractDictionaryDTO> result = new ArrayList<>();
        mapList.forEach((k,v)-> {
            ContractDictionaryDTO contractDictionaryDTO = new ContractDictionaryDTO();
            contractDictionaryDTO.setCode(k);
            contractDictionaryDTO.setName(v.get(0).getFirstBodyName());
            List<ContractDictionaryChildrenDTO> children = new ArrayList<>();
            v.stream()
                .forEach(m -> {
                    ContractDictionaryChildrenDTO child = new ContractDictionaryChildrenDTO();
                    child.setChildrenCode(m.getSecondBodyCode());
                    child.setChildrenName(m.getSecondBodyName());
                    children.add(child);
                });
            contractDictionaryDTO.setChildren(children);
            result.add(contractDictionaryDTO);
        });
        return result;
    }

    @Override
    public String orderCenterFileUpload(String fileName, byte[] bytes, String fileType) {
        String fileBody = KiteBase64Util.encodeDataByte(bytes);
        Map<String, Object> resultMap = infServiceBus.orderCenterFileUpload(fileName, fileType, fileBody);
        return KiteMapUtils.getString(resultMap, "FILE_ID");
    }
    @Override
    public List<JSONObject> orderCenterHttpFileUpload(File toFile,byte[] bytes) {

        Map<String, Object> request = new HashMap<>();
        request.put("files", toFile);
        request.put("infoType", "contract");
        request.put("userLogin",  "hq-ceshi17");//使用固定工号上传
        request.put("subInfoType", "printContract");
        // 获取服务配置信息
        IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
        InfService infService = orderQueryService.queryServiceBySvcCode(CallClientEnum.CREATE_UPLOADCONTRACT.getServiceCode(),
            CallClientEnum.CREATE_UPLOADCONTRACT.getCenterCode());
        if (infService == null) {
            ErrorConsts.SERVICE_UNREGISTERED.throwOut(
                CallClientEnum.CREATE_UPLOADCONTRACT.getCenterCode() + ":" + CallClientEnum.CREATE_UPLOADCONTRACT.getServiceCode());
        }
        String url = SpringUtil.getBean(ICuccQueryInfService.class).getUrlByType(infService);

        String data = KiteHttpUtils.postByteHttpFile(SpringUtil.getBean(ICuccQueryInfService.class).getUrlByType(infService), bytes, toFile.getName(),request);
        Map<String, Object> resultObject = JSON.parseObject(data, Map.class);
        if("0000".equals(KiteMapUtils.getString(resultObject, "code"))){
            List<JSONObject> dataList = (List<JSONObject>) resultObject.get("data");
            return dataList;
        }else{
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(CallClientEnum.CREATE_UPLOADCONTRACT.getServiceCode(),KiteMapUtils.getString(resultObject, "message"));
        }
        return null;
    }
    @Override
    public QryStockAttachMentUrlRspDTO getStockAttachmentUrl(QryStockAttachMentUrlReqDTO qryStockAttachMentUrlReqDTO) {
        QryStockAttachMentUrlRspDTO qryStockAttachMentUrlRsp = new QryStockAttachMentUrlRspDTO();
        if (KiteObjectUtils.isEmpty(qryStockAttachMentUrlReqDTO)) {
            return qryStockAttachMentUrlRsp;
        }
        if (StrTools.isEmpty(qryStockAttachMentUrlReqDTO.getEsbFileName())) {
            return qryStockAttachMentUrlRsp;
        }
        Map<String, Object> param = new HashMap<>();
        Map uniBssBody = new HashMap();
        param.put("OP_CODE", "QRY_DWONLOAD_FILE_APPLY");
        param.put("UNI_BSS_BODY", uniBssBody);
        uniBssBody.put("PROVINCE_CODE", qryStockAttachMentUrlReqDTO.getProvinceCode());
        uniBssBody.put("ESB_FILE_NAME", qryStockAttachMentUrlReqDTO.getEsbFileName());

        String url = "";
        Map result = HttpsCallClient.postObjMap(LocalCallClientEnum.STOCK_ATTACHMENT_URL_INFO.getCenterCode(), LocalCallClientEnum.STOCK_ATTACHMENT_URL_INFO.getServiceCode(), param, null);
        if (KiteMapUtils.isNotEmpty(result)) {
            String respDesc = KiteMapUtils.getString(result, "RSP_CODE");
            qryStockAttachMentUrlRsp.setRspCode(respDesc);
            if (KiteStringUtils.isEqual("0000", respDesc)) {
                url = (String) result.get("URL");
                qryStockAttachMentUrlRsp.setUrl(url);
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(LocalCallClientEnum.STOCK_ATTACHMENT_URL_INFO.getServiceCode(), "获取存量附件链接失败", "获取存量附件链接失败");
            }
        }
        else {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.STOCK_ATTACHMENT_URL_INFO.getServiceCode(), "获取存量附件链接失败", "获取存量附件链接失败");
        }

        return qryStockAttachMentUrlRsp;
    }
}
